package com.ssfeng.youxia.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import utils.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by liyuhang on 2019-09-15.
 */
public class KickoutSessionFilter extends AccessControlFilter {

    private static final Logger logger = LoggerFactory.getLogger(KickoutSessionFilter.class);

    private static final org.apache.log4j.Logger logger4j = org.apache.log4j.Logger.getLogger(KickoutSessionFilter.class);

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        logger.info("自定义shiroFilter");
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        if (!StringUtils.isEmpty(session)) {
            if (!StringUtils.isEmpty(session.getAttribute(SessionUtils.SESSION_KICKOUT_KEY))) {
                return false;
            }
        }
        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = getSubject(request, response);
        subject.logout();
        boolean isAjax = WebUtils.isAjaxRequest((HttpServletRequest) request);
        if (isAjax) {
            Map<String, String> map = new HashMap<>();
            map.put("msg", "该账号已被踢出登录");
            map.put("code", "-1");
            this.outJson(response,map);
        }
        String basePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+((HttpServletRequest)request).getContextPath()+"/";
        org.apache.shiro.web.util.WebUtils.issueRedirect(request,response,basePath+"error/kickout.html");
        return true;
    }

    private void outJson(ServletResponse hresponse, Map<String, String> resultMap)
            throws IOException {
        try {
            hresponse.setCharacterEncoding("UTF-8");
            PrintWriter out = hresponse.getWriter();
            out.println();
            out.flush();
            out.close();
        } catch (Exception e) {
            logger.error("",e);
        }
    }
}
